<template>
	<view class="container">
		<!--  <map id="myMap" :latitude="latitude" :longitude="longitude" :markers="markers" :scale="scale" :enable-zoom="true"
      @markertap="onMarkerTap" @regionchange="onRegionChange" @scale="handleScale">
    </map> -->

		<view class=""></view>

		<!-- 聊天面板 -->
		<view class="chat-panel" :class="{ 'panel-show': showPanel }">
			<!-- 聊天面板头部 -->
			<!-- @click="toggleChatPanel" -->
			<view class="panel-header">
				<scroll-view class="message-title-area" scroll-x :scroll-left="scrollLeft">
					<view class="title-area" v-if="!isOwner" @click.stop="handleCall(carOwnerName)">
						<text class="title">{{ carOwnerName }}</text>
						<image src="/static/callout.png" class="callout-icon"></image>
					</view>
					<text
						class="gary-title"
						:class="{ 'gary-title-active': carOwnerUid === item.uid }"
						v-else
						v-for="item in lineOrdersArr"
						:key="item.uid"
						@click.stop="handleCheck(item.uid)"
					>
						尾号{{ item.phone }}
					</text>
				</scroll-view>

				<!-- <view class="toggle-btn">{{ showPanel ? '收起' : '展开' }}</view> -->
			</view>
			<!-- 聊天内容区域 -->
			<scroll-view class="message-area" scroll-y :scroll-into-view="toView">
				<view v-for="(msg, index) in messages" :key="index" :class="['message', msg.sender]" v-if="dataTag === msg.tag">
					<image :src="msg.toHeader" class="header-icon other-icon" :class="{ 'show-to-icon': msg.sender === 'other' }" mode="aspectFill" @click="handleCheck"></image>
					<text class="content">{{ msg.content }}</text>
					<image :src="msg.fromHeader" class="header-icon me-icon" :class="{ 'show-me-icon': msg.sender === 'me' }" mode="aspectFill" @click="handleCheck"></image>
				</view>
				<view :id="`bottom-anchor-${messages.length}`"></view>
			</scroll-view>

			<!-- 输入区域 -->
			<view class="input-area">
				<input v-model="inputMsg" placeholder="说点什么..." @confirm="handleSendMessage" confirm-type="send" />
				<button class="common-btn" @click="handleSendMessage">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
import config from '@/config';
import { sendTextMessage, pullLocation } from '@/utils/ws';
export default {
	data() {
		return {
			toView: '',
			lindId: '',
			// 地图相关
			latitude: null,
			longitude: null,
			scale: 10,
			markers: [],
			// 聊天相关
			showPanel: false,
			inputMsg: '',
			messages: [],
			scrollTop: 0,
			socket: null,
			carOwnerName: '',
			scrollLeft: 0,
			isOwner: false,
			lineOrdersArr: [],
			dataTag: ''
		};
	},
	onShow(options) {},
	onUnload() {
		uni.$off('locationsMessagesChanged');
		uni.$off('textMessagesChanged');
	},
	onLoad(options) {
		const list = uni.getStorageSync('lineOrders');
		if (!list || !list.length) {
			uni.showToast({
				title: '无聊天对象',
				icon: 'none',
				mask: true
			});
			uni.switchTab({
				url: '/pages/home/index'
			});
		}

		this.lineOrdersArr = list;

		console.log(options, '位置聊天组件');
		this.lindId = options.lid;
		this.carOwnerUid = options.carOwnerUid;
		this.carOwnerName = options.carOwnerName;
		this.dataTag = `${uni.getStorageSync('userInfo').id}-${this.carOwnerUid}`;
		let sendIdsData = [];
		// 乘客位置聊天
		if (options.type === 'passenger') {
			this.isOwner = false;
			sendIdsData = [options.carOwnerUid, uni.getStorageSync('userInfo').id];
		} else {
			// 车主位置聊天
			this.isOwner = true;
			this.lineOrdersArr = uni.getStorageSync('lineOrdersArr');
			if (this.lineOrdersArr.length > 0) {
				this.carOwnerUid = this.lineOrdersArr[0].uid;
			}
			this.lineOrdersArr.forEach((item) => {
				sendIdsData.push(item.uid);
			});
			sendIdsData.push(uni.getStorageSync('userInfo').id);
		}
		// 定时任务前先获取一次
		pullLocation(sendIdsData);
		// 定时拉取位置信息
		setInterval(() => {
			pullLocation(sendIdsData);
		}, 3000);

		uni.$on('locationsMessagesChanged', (nMsg) => {
			this.markers =
				nMsg &&
				nMsg.map((item) => {
					if (item.id === uni.getStorageSync('userInfo').id) {
						this.latitude = item.latitude;
						this.longitude = item.longitude;
					}
					return {
						id: item.id,
						latitude: item.latitude,
						longitude: item.longitude,
						iconPath: item.avatar,
						width: 40,
						height: 40,
						// 设置圆角
						borderRadius: 10,
						label: {
							content: `${uni.getStorageSync('userInfo').id === item.id ? '我' : item.phone.slice(-4)}`,
							color: '#FFFFFF',
							fontSize: 12,
							bgColor: uni.getStorageSync('userInfo').id === item.id ? '#FF7937' : '#00CFAB',
							borderRadius: 8,
							padding: 6,
							textAlign: 'center',
							anchorX: -40, // 水平居中（0 表示label与marker水平中心对齐）
							anchorY: 0 // 40 + 8 // 控制文本位置
						}
					};
				});
		});

		uni.$on('textMessagesChanged', (newMsg) => {
			this.messages.push({
				sender: newMsg.from_uid === uni.getStorageSync('userInfo').id ? 'me' : 'other',
				fromHeader: newMsg.from_avatar,
				toHeader: newMsg.to_avatar,
				content: newMsg.message_content,
				tag: newMsg.from_uid === uni.getStorageSync('userInfo').id ? `${newMsg.from_uid}-${newMsg.to_uid}` : `${newMsg.to_uid}-${newMsg.from_uid}`
			});
		});

		this.onMarkerTap(list[0].uid);
	},
	methods: {
		handleCall(phoneNumber) {
			this.$makePhoneCall(phoneNumber, {
				success: () => {
					// uni.showToast({ title: '正在拨号...', icon: 'none' });
				},
				fail: (err) => {
					uni.showToast({ title: '拨号失败: ' + err.errMsg, icon: 'none' });
				}
			});
		},
		// 地图相关
		onMarkerTap(e) {
			console.log(e, 'markerId');

			if (e === uni.getStorageSync('userInfo').id) {
				this.showPanel = false;
				uni.showToast({
					title: '无法与自己对话',
					icon: 'none'
				});
			} else {
				this.showPanel = true;
			}

			setTimeout(() => {
				this.carOwnerUid = e;
				this.dataTag = `${uni.getStorageSync('userInfo').id}-${e}`;

				this.getChatRecord();
			}, 1000);

			if (this.showPanel) {
				this.scrollToBottom();
			}
		},
		// 获取聊天记录
		async getChatRecord() {
			let res = await this.$http.get('/h5/chat/getChatRecord', {
				page: 1,
				size: 20,
				line_id: this.lindId,
				from_uid: uni.getStorageSync('userInfo').id,
				to_uid: this.carOwnerUid
			});

			this.messages = res.data.pageList.list
				.map((item) => {
					return {
						sender: item.from_uid === uni.getStorageSync('userInfo').id ? 'me' : 'other',
						fromHeader: item.fromUser.avatar_full,
						toHeader: item.toUser.avatar_full,
						content: item.content,
						tag: item.from_uid === uni.getStorageSync('userInfo').id ? `${item.from_uid}-${item.to_uid}` : `${item.to_uid}-${item.from_uid}`
					};
				})
				.reverse();
			this.scrollToBottom();
		},
		toggleChatPanel() {
			this.showPanel = !this.showPanel;
			if (this.showPanel) {
				this.scrollToBottom();
			}
		},
		onRegionChange(e) {
			// console.log('地图区域变化', e);
		},
		handleScale(e) {
			// console.log('缩放比例变化', e);
		},
		//聊天相关
		scrollToBottom() {
			this.$nextTick(() => {
				setTimeout(() => {
					this.toView = 'bottom-anchor-' + this.messages.length;
				}, 50);
			});
		},
		// 发送消息
		handleSendMessage() {
			if (!this.inputMsg.trim()) {
				uni.showToast({
					title: '请输入内容',
					icon: 'none'
				});
				return;
			}
			// 获取当前用户信息
			const userInfo = uni.getStorageSync('userInfo');
			this.messages.push({
				sender: 'me',
				fromHeader: userInfo.avatar,
				content: this.inputMsg,
				tag: `${uni.getStorageSync('userInfo').id}-${this.carOwnerUid}`
			});

			sendTextMessage(userInfo.id, this.carOwnerUid, this.lindId, this.inputMsg);
			this.inputMsg = '';
			this.scrollToBottom();
		},
		handleCheck(uid) {
			this.carOwnerUid = uid;
			this.dataTag = `${uni.getStorageSync('userInfo').id}-${uid}`;
			this.getChatRecord();
		}
	}
};
</script>

<style lang="scss" scoped>
#myMap {
	width: 100%;
	height: 100vh;
	z-index: 888;
}

.chat-panel {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	width: 100%;
	height: 100vh;
	background-color: #f5f5f6;
	border-top-left-radius: 48rpx;
	border-top-right-radius: 48rpx;
	display: flex;
	flex-direction: column;
	transform: translateY(100%);
	transition: all 0.3s ease;
	z-index: 9999999;
}

.panel-show {
	bottom: 0;
	transform: translateY(0);
}

.panel-header {
	padding: 34rpx 40rpx;
	background-color: #ffffff;
	display: flex;
	justify-content: center;
	align-items: center;
	border-top-left-radius: 48rpx;
	border-top-right-radius: 48rpx;
	position: relative;

	.title {
		font-weight: 500;
		font-size: 32rpx;
		color: #0b1f20;
	}

	.toggle-btn {
		font-family: Source Han Sans CN, Source Han Sans CN;
		font-weight: 400;
		font-size: 28rpx;
		color: #ff7937;
		display: inline-block;
		width: 60rpx;
	}
}

.message-area {
	flex: 1;
	margin: 20rpx 24rpx 20px 24rpx;
	overflow-y: auto;
	height: 460rpx;
}

.message {
	margin-bottom: 52rpx;
	position: relative;
	display: flex;
	align-items: center;

	.header-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #f5f5f6;
	}
}

.me {
	display: flex;
	justify-content: end;
	margin-right: 48rpx;

	.content {
		max-width: 75%;
		padding: 20rpx 14rpx 18rpx 20px;
		border-radius: 16rpx 0 16rpx 16rpx;
		background-color: #ffffff;
		font-size: 28rpx;
		color: #0b1f20;
		margin-right: 20rpx;
	}
}

.other {
	margin-right: auto;

	.content {
		max-width: 75%;
		padding: 20rpx 14rpx 18rpx 20px;
		border-radius: 0 16rpx 16rpx 16rpx;
		background-color: #ffffff;
		font-size: 28rpx;
		color: #0b1f20;
		margin-left: 20rpx;
	}
}

.meheader-icon {
}

.input-area {
	display: flex;
	background: #ffffff;
	padding: 24rpx;

	input {
		flex: 1;
		height: 72rpx;
		background: #f5f5f6;
		border-radius: 36rpx;
		padding: 0 20rpx;
		border: none;
		margin-right: 20rpx;
	}

	.input-placeholder {
		font-family: Source Han Sans CN, Source Han Sans CN;
		font-weight: 400;
		font-size: 24rpx;
		color: #9ca3af;
		letter-spacing: 1px;
	}

	button {
		width: 160rpx;
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		font-family: Source Han Sans CN, Source Han Sans CN;
		font-weight: 500;
		font-size: 32rpx;
		color: #ffffff;
		border-radius: 36rpx;
	}
}

.show-me-icon,
.show-to-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: #f5f5f6;
}

.me {
	.show-to-icon {
		display: none;
	}

	.other-icon {
		display: none;
	}
}

.other {
	.me-icon {
		position: absolute;
	}
}

.message-title-area {
	padding-left: 20rpx;
	width: calc(100% - 80rpx);

	.title {
		margin-right: 16rpx;
	}
}

.gary-title {
	font-weight: 400;
	font-size: 28rpx;
	color: #666666;
	margin-right: 16rpx;
}

.gary-title-active {
	font-weight: 500;
	font-size: 32rpx;
	color: #0b1f20;
}
.title-area {
	display: flex;
	align-items: center;
	.callout-icon {
		width: 40rpx;
		height: 40rpx;
		margin-left: -12rpx;
	}
}
</style>

<style>
.amap-icon {
	width: 40rpx !important;
	height: 40rpx;
	border-radius: 50%;
}
</style>
